<?php

namespace app\api\services;

use app\common\controller\WxAccessToken;
use think\facade\Log;

class WXQrcode
{
    use WxAccessToken;

    /**
     * 生成用户临时二维码
     * @return string|null
     */
    public function shareTemporaryQrCode ($uuid): ?string
    {
        $api = self::$wechat->getClient();
        Log::info('getAccessToken ' . self::getAccessToken());
        $response = $api->post("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . self::getAccessToken(), [
            'body' => json_encode([
                "expire_seconds" => 2592000,
                "action_name"    => "QR_STR_SCENE",
                "action_info"    => [
                    "scene" => [
                        "scene_str" => $uuid //用户唯一标识
                    ]
                ]
            ])
        ]);
        $ret = json_decode($response->getContent(), true);
        if (isset($ret['errcode']) && $ret['errcode'] == 40001) {
            Log::error('生成用户二维码失败' . json_encode($ret));
            return null;
        }
        $response_showqrcode = $api->get('https://mp.weixin.qq.com/cgi-bin/showqrcode', [
            'ticket' => $ret['ticket'],
        ]);

        $path = '/wx_qrcode/temporary/' . date('Ymd');
        $root = ROOT_PATH . $path;
        if (!file_exists($root) || !is_dir($root)) {
            mkdir($root, 0777, true);
        }

        try {
            file_put_contents($root . '/' . $uuid . '.png', $response_showqrcode->getContent());
        } catch (\Exception $e) {
            Log::error('生成用户二维码' . $e->getMessage());
            return null;
        }
        return $path;
    }

    /**
     * 生成推广员永久二维码
     * @return string|null
     */
    public function sharePermanentQrCode ($uuid): ?string
    {
        $api = self::$wechat->getClient();
        Log::info('getAccessToken ' . self::getAccessToken());
        $response = $api->post("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . self::getAccessToken(), [
            'body' => json_encode([
                "action_name" => "QR_LIMIT_STR_SCENE",
                "action_info" => [
                    "scene" => [
                        "scene_str" => $uuid //用户唯一标识
                    ]
                ]
            ])
        ]);
        $ret = json_decode($response->getContent(), true);
        if (isset($ret['errcode']) && $ret['errcode'] == 40001) {
            Log::error('生成用户二维码失败' . json_encode($ret));
            return null;
        }
        $response_showqrcode = $api->get('https://mp.weixin.qq.com/cgi-bin/showqrcode', [
            'ticket' => $ret['ticket'],
        ]);

        $path = '/wx_qrcode/permanent/' . date('Ymd');
        $root = ROOT_PATH . $path;
        if (!file_exists($root) || !is_dir($root)) {
            mkdir($root, 0777, true);
        }

        try {
            file_put_contents($root . '/' . $uuid . '.png', $response_showqrcode->getContent());
        } catch (\Exception $e) {
            Log::error('生成用户二维码' . $e->getMessage());
            return null;
        }
        return $path;
    }

    public function send ($FromUserName)
    {

        $curl = curl_init();
        curl_setopt_array($curl, array (
            CURLOPT_URL            => 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . self::getAccessToken(),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => '',
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => 'POST',
            CURLOPT_POSTFIELDS     => ' {
    "touser":"' . $FromUserName . '",
    "msgtype":"text",
    "text":{
        "content":"欢迎关注【月色到家·健康养生】\\n1、查看公众号左下角的“立即下单”，全天24小时均可下单。\\n2、请下单后耐心等待，技师会在5分钟内接单出发并联系您！"
    }
 }'
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        Log::info('send ' . json_encode($response));
    }

}
